package com.mc.fastkit.widget

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.Request
import com.bumptech.glide.request.RequestOptions
import com.mc.fastkit.ext.cast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * ImageRequest
 * @author: MasterChan
 * @date: 2024-08-29 13:44
 */
object ImageRequest {

    fun ImageView.load(data: Any?, requestOptions: RequestOptions.() -> Unit = {}): Request? {
        val options = RequestOptions()
        requestOptions.invoke(options)
        return Glide.with(context).load(data).apply(options).into(this).request
    }

    fun ImageView.loadCircle(circleUrl: Any?, requestOptions: RequestOptions.() -> Unit = {}) {
        if (circleUrl == null) return
        if (this.context is Activity) {
            if ((this.context as Activity).isFinishing || (this.context as Activity).isDestroyed) return
        }
        val options = RequestOptions()
        requestOptions.invoke(options)
        Glide.with(this).load(circleUrl)
            .apply(options)
            .transform(CircleCrop()).into(this)
    }

    fun ImageView.loadCorner(url: Any?, corner: Int, placeholder: Int = 0, error: Int = 0) {
        if (url == null) return
        if (this.context is Activity) {
            if ((this.context as Activity).isFinishing || (this.context as Activity).isDestroyed) return
        }
        val transform = Glide.with(this).load(url).placeholder(placeholder).error(error)
            .transform(CenterCrop(), RoundedCorners(corner))
        transform.into(this)
    }

    suspend inline fun <reified T> execute(
        context: Context,
        data: Any?,
        requestOptions: RequestOptions.() -> Unit = {}
    ): T {
        val options = RequestOptions()
        requestOptions.invoke(options)
        val requestManager = Glide.with(context)
        val builder = when (T::class.java) {
            Bitmap::class.java -> requestManager.asBitmap()
            GifDrawable::class.java -> requestManager.asGif()
            Drawable::class.java -> requestManager.asDrawable()
            else -> requestManager.asFile()
        }
        return withContext(Dispatchers.IO) {
            builder.load(data).apply(options).submit().get().cast()
        }
    }
}